package com.anti.commom.core.utils;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.http.ContentType;
import cn.hutool.log.Log;
import com.alibaba.fastjson.JSON;
import com.anti.commom.api.Result;
import com.anti.commom.core.exception.enums.AuthExceptionEnum;
import com.anti.commom.core.exception.enums.PermissionExceptionEnum;
import lombok.SneakyThrows;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 响应工具类
 */
public class ResponseUtil {
    private static final Log log = Log.get();

    /**
     * 响应异常，直接向前端写response，用于异常处理器捕获不到时手动抛出
     */
    public static void responseExceptionError(Integer code,
                                              String message) throws IOException {
        HttpServletResponse response = HttpServletUtil.getResponse();
        response.setCharacterEncoding(CharsetUtil.UTF_8);
        response.setContentType(ContentType.JSON.toString());
        Result<Object> result = Result.fail(code, message);
        String errorResponseJsonData = JSON.toJSONString(result);
        response.getWriter().write(errorResponseJsonData);
    }
    /**
     * 渲染异常json
     */
    public static Object handleError(Integer code, String message) {
        return handleErrorWithoutWrite(code, message, "");
    }

    /**
     * 响应异常，向前端返回ErrorResponseData的json数据，用于全局异常处理器
     */
    public static Object handleErrorWithoutWrite(Integer code, String message, String exceptionClazz) {
        HttpServletRequest request = HttpServletUtil.getRequest();
        boolean ajaxRequest = isAjax(request);
        if(ajaxRequest) {
            Result<Object> result = Result.fail(code,exceptionClazz, message);
            return result;
        } else {
            if(code.equals(PermissionExceptionEnum.NO_PERMISSION.getCode()) ||
                    code.equals(PermissionExceptionEnum.NO_PERMISSION_OPERATE.getCode())) {
                //跳转到全局错误处理，没有权限访问页面，403页面
                return new ModelAndView("redirect:/403");
            } else if(code.equals(PermissionExceptionEnum.URL_NOT_EXIST.getCode())) {
                //跳转到全局错误处理，路径不存在，404页面
                return new ModelAndView("redirect:/404");
            } else {
                //跳转到全局错误处理，服务器异常，500页面
                return new ModelAndView("redirect:/500");
            }
        }
    }
    /**
     * 响应异常，直接向前端写response，用于异常处理器捕获不到时手动抛出
     */
    @SneakyThrows
    public static void handleErrorWithWrite(Integer code,
                                            String message,
                                            String exceptionClazz) {
        HttpServletRequest request = HttpServletUtil.getRequest();
        HttpServletResponse response = HttpServletUtil.getResponse();
        boolean ajaxRequest = isAjax(request);
        if(ajaxRequest) {
            try {
                response.setCharacterEncoding(CharsetUtil.UTF_8);
                response.setContentType(ContentType.JSON.toString());
                Result<Object> result = Result.fail(code,exceptionClazz, message);
                String errorResponseJsonData = JSON.toJSONString(result);
                response.getWriter().write(errorResponseJsonData);
            } catch (IOException e) {
                //log.error(">>> 响应异常，请求号为：{}", RequestNoContext.get());
                e.printStackTrace();
            }
        } else {
            if(code.equals(PermissionExceptionEnum.NO_PERMISSION.getCode()) ||
                    code.equals(PermissionExceptionEnum.NO_PERMISSION_OPERATE.getCode())) {
                //跳转到全局错误处理，没有权限访问页面，403页面
                response.sendRedirect(request.getContextPath() + "/global/sessionError?errorCode=" +  PermissionExceptionEnum.NO_PERMISSION.getCode());
            } else if(code.equals(PermissionExceptionEnum.URL_NOT_EXIST.getCode())) {
                //跳转到全局错误处理，路径不存在，404页面
                response.sendRedirect(request.getContextPath() + "/global/sessionError?errorCode=" +  PermissionExceptionEnum.URL_NOT_EXIST.getCode());
            } else if(code.equals(AuthExceptionEnum.REQUEST_TOKEN_EMPTY.getCode())) {
                //跳转到全局错误处理，登录页，请先登录
                response.sendRedirect(request.getContextPath() + "/global/sessionError?errorCode=" +  AuthExceptionEnum.NOT_LOGIN.getCode());
            } else {
                //跳转到全局错误处理，登录过期需要登录
                response.sendRedirect(request.getContextPath() + "/global/sessionError");
            }
        }
    }
    /**
     * 判断网络请求是否为ajax
     * @param req
     * @return
     */
    private static boolean isAjax(HttpServletRequest req) {
        String contentTypeHeader = req.getHeader("Content-Type");
        String acceptHeader = req.getHeader("Accept");
        String xRequestedWith = req.getHeader("X-Requested-With");
        return (contentTypeHeader != null && contentTypeHeader.contains("application/json"))
                || (acceptHeader != null && acceptHeader.contains("application/json"))
                || "XMLHttpRequest".equalsIgnoreCase(xRequestedWith);
    }
}
